网络流,费用流模板

模板,仅供参考

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include<bits/stdc++.h>
using namespace std;
inline int read(){
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
const int inf=2147483647;
const int maxn=105;
const int maxm=5005;
struct edge{
int to,next,flow;
}e[maxm*2];
int h[maxn],cnt=1;
inline void addedge(int u,int v,int f){
e[++cnt]=(edge){v,h[u],f};h[u]=cnt;
e[++cnt]=(edge){u,h[v],0};h[v]=cnt;
}
int n,m,s,t;
int dis[maxn],cur[maxn];
inline bool bfs(){
memset(dis,-1,sizeof(dis));
for(int i=1;i<=n;i++)cur[i]=h[i];
dis[s]=0;
queue<int>q; q.push(s);
while(!q.empty()){
int x=q.front();q.pop();
for(int i=h[x];i;i=e[i].next){
int y=e[i].to;
if(dis[y]==-1&&e[i].flow){
dis[y]=dis[x]+1;
q.push(y);
}
}
}
return dis[t]!=-1;
}
int dfs(int x,int maxf){
if(x==t)return maxf;
int res=0;
for(int i=cur[x];i;i=e[i].next){
int y=e[i].to;
if(e[i].flow&&dis[y]==dis[x]+1){
int dlt=dfs(y,min(maxf,e[i].flow));
e[i].flow-=dlt;
e[i^1].flow+=dlt;
res+=dlt; maxf-=dlt;
if(!maxf)return res;
}
cur[x]=i;
}
return res;
}
inline int dinic(){
int res=0;
while(bfs())res+=dfs(s,inf);
return res;
}
int main(){
n=read();m=read();s=read();t=read();
for(int i=1;i<=m;i++){
int u=read(),v=read(),w=read();
addedge(u,v,w);
}
cout<<dinic()<<"\n";
return 0;
}

0%